unit SmallStruct.Database.TSSDatabaseConnectionFactory;

interface

uses SmallStruct.Core.TSSObjectFactory,
  SmallStruct.Database,
  SmallStruct.Configuration;

type
  TSSDatabaseConnectionFactory = class(TSSObjectFactory, ISSDatabaseConnectionFactory)
  private
    function CreateDatabaseConnection(DatabaseConnectionConfiguration: ISSDatabaseConnectionConfiguration): ISSDatabaseDriver;
    function GetDatabaseConnection(const ADatabaseConnectionName: string): ISSDatabaseDriver;
  end;

implementation

uses SmallStruct.Core,
  SmallStruct.Core.TSSObjectContext,
  SmallStruct.Database.TSSDatabaseDriver;

{ TSSDatabaseConnectionFactory }

function TSSDatabaseConnectionFactory.CreateDatabaseConnection(DatabaseConnectionConfiguration: ISSDatabaseConnectionConfiguration): ISSDatabaseDriver;
var
  DriverClass: TSSDatabaseDriverClass;
  Driver: TSSDatabaseDriver;
  Context: TSSObjectContext;
begin
  DriverClass := TSSDatabaseDriverClass((GetSystemObject.GetClassTable as ISSClassTable).QueryClass(DatabaseConnectionConfiguration.GetDriverClassName));
  Driver := DriverClass.Create(nil);
  Context := TSSObjectContext.Create(nil);
  Context.SetConfiguration(DatabaseConnectionConfiguration);
  Driver.SetContext(Context);
  Driver.InitObject;
  Result := Driver;
end;

function TSSDatabaseConnectionFactory.GetDatabaseConnection(const ADatabaseConnectionName: string): ISSDatabaseDriver;
begin
  if (GetSystemObject.GetGlobalObjectTable as ISSObjectContainer).FindObject(ADatabaseConnectionName) >= 0 then
    Result := (GetSystemObject.GetGlobalObjectTable as ISSObjectContainer).GetObject(ADatabaseConnectionName) as TSSDatabaseDriver
  else
  begin
    Result := CreateDatabaseConnection((GetSystemObject.GetConfigurationTable as ISSConfigurationTable).QueryDatabaseConnectionConfiguration(ADatabaseConnectionName) as ISSDatabaseConnectionConfiguration);
    (GetSystemObject.GetGlobalObjectTable as ISSObjectContainer).AppendObject(ADatabaseConnectionName, Result.GetObjectInstance);
  end;
end;

end.
